package com.kitchen.ui.dialog.storage
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	
	public class StorageGridCell extends Sprite
	{
		public var w:int;
		public var h:int;
		public var checked:Boolean;
		public var id:int;
		public var data:Object;
		private var empty:Boolean;
		private var bitmap:Bitmap;
		private var loader:Loader;
		private static var bitdata:BitmapData = null;
		
		public function StorageGridCell(bitdata:BitmapData, id:int, data:Object=null)
		{
			this.h = 50;
			this.w = 50;
			this.id = id;
			this.data = data;
			this.checked = false;
			this.bitmap = new Bitmap(this.getBitmapData(bitdata));
			this.addChild(this.bitmap);
			this.layout(bitdata);
			if(this.data == null){
				this.empty = true;
				this.bitmap.x = -100;
			}else{
				this.empty = false;
				this.useHandCursor = true;
				this.buttonMode = true;
				loader = new Loader();
				loader.load(new URLRequest(this.data.sUrl));
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderComplete);
			}
		}
		//设置选中状态
		public function setChecked(check:Boolean):void{
			if(this.empty){
				return;
			}
			this.checked = check;
			if(this.checked){
				this.bitmap.x = -50;
			}else{
				this.bitmap.x = 0;
			}
		}
		
		private function layout(bitdata:BitmapData):void{
			var shape:Shape = new Shape();
			shape.graphics.beginFill(0xffffff, 1);
			shape.graphics.drawRect(0, 0, this.w, this.h);
			shape.graphics.endFill();
			this.mask = shape;
			this.addChild(shape);
		}
		
		protected function getBitmapData(bitdata:BitmapData):BitmapData{
			if(StorageGridCell.bitdata === null){
				var cbitdata:BitmapData = new BitmapData(this.w*3, this.h);
				cbitdata.copyPixels(bitdata, new Rectangle(788, 200, this.w*3, this.h), new Point());
				StorageGridCell.bitdata = cbitdata;
			}
			return StorageGridCell.bitdata;
		}
		
		//cell content
		private function loaderComplete(event:Event):void{
			this.loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loaderComplete);
			var bitdata:BitmapData = new BitmapData(40, 40);
			bitdata.copyPixels(Bitmap(this.loader.content).bitmapData, new Rectangle(0, 0, 40, 40), new Point());
			var bitmap:Bitmap = new Bitmap(bitdata);
			this.loader.unload();
			this.loader = null;
			bitmap.x = 5;
			bitmap.y = 5;
			this.addChild(bitmap);
		}
	}
}